package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLInvalidAuthorizationSpecException;

/**
 * 全局异常处理器
 *
 * @author Xiao
 * @date 2021/9/23
 */
@ControllerAdvice(annotations = {Controller.class, RestController.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    /**
     * SQLIntegrityConstraintViolationException异常处理
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        //Duplicate entry 'zhangsan@reggie.com' for key 'idx_username'
        log.error(ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry")) {
            String username = ex.getMessage().split("'")[1];
            return R.error(username + " 已存在！");
        }
        return R.error("网络异常，请稍后重试。");
    }

    /**
     * CustomException异常处理
     * @param cex
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException cex) {
        log.info(cex.getMessage());
        return R.error(cex.getMessage());
    }
}
